/**
 * Copyright (c) 2021-2022 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include "ecma_profiling.h"
#include "plugins/ecmascript/runtime/js_function.h"

namespace ark::ecmascript {

void CallProfile::Update(ECMAObject *jsFunc, EcmaCallProfilingTable *table)
{
    if (calleesIdx_[0] == MEGAMORPHIC) {
        return;
    }
    auto method = jsFunc->GetCallTarget();
    for (size_t i = 0; i < MAX_FUNC_NUMBER; ++i) {
        if (calleesIdx_[i] == UNKNOWN) {
            auto idx = table->InsertNewObject(jsFunc);
            if (idx) {
                // Atomic with release order reason: profile data may be updated while the compiler thread loads it
                reinterpret_cast<std::atomic<Type> *>(&calleesIdx_[i])->store(idx.value(), std::memory_order_release);
            }
            return;
        }
        ASSERT(calleesIdx_[i] > 0 && calleesIdx_[i] <= std::numeric_limits<Type>::max() - 1U);
        if (table->GetObject(calleesIdx_[i])->GetCallTarget() == method) {
            return;
        }
    }
    // NOTE(schernykh): Create way for clear call profiling table, and clear it in this place.
    // Atomic with release order reason: profile data may be updated while the compiler thread loads it
    reinterpret_cast<std::atomic<Type> *>(&calleesIdx_[0])->store(MEGAMORPHIC, std::memory_order_release);
}

}  // namespace ark::ecmascript
